/**
 * bit 流缓冲区
 * 张勇 41204@qq.com
 */
#pragma once

#include "std_err.h"
#include "utils.h"

typedef struct {
	uint8_t* bytes;		// 数据缓冲区
	size_t size;	// 可容纳的 Bit 数量
	size_t bitc;	// 实际有效的 Bit 数量
} bit_stream_t;

#ifdef __cplusplus
extern "C" {
#endif

/// 获取第几个bit
static inline uint8_t bit_stream_get(bit_stream_t* bits, size_t idx) { return (idx > bits->bitc) ? 0: BITn(bits->bytes, idx); }
/// 清零
static inline void bit_stream_clear(bit_stream_t* bits) { bits->bitc = 0; memset(bits->bytes, 0, (bits->size >> 3)); }
/// 占用多少个字节
static inline size_t bit_stream_nbytes(bit_stream_t* bits) { return (bits->bitc >> 3) + ((bits->bitc & 7) ? 1 : 0); }
/// 在末尾添加一个bit
std_err_t bit_stream_append(bit_stream_t* bits, uint8_t bit);

#ifdef __cplusplus
}
#endif
